<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

class Form {

  protected $_desc = '';
  protected $_title = '';
  protected $_fields;
  protected $_extras = array();

  /**
   * init a from from data
   * @param  array $data 
   */
  public function __construct($data = NULL) {
    $this->init();
    $this->setData($data);
  }

  public function init() {
    throw new Exception("class " . __CLASS__ . " has no method init");
  }

  public function asHtml() {
    $path = ROOT_DIR . "partial/Form/asHtml.tpl";
    include_once $path;
  }

  public function asDl() {
    $path = ROOT_DIR . "partial/Form/asDl.tpl";
    include_once $path;
  }

  public function asDiv() {
    $path = ROOT_DIR . "partial/Form/asDiv.tpl";
    include_once $path;
  }

  public function setData($data) {
    if (is_array($data)) {
      foreach ($this->_fields as $name => $field) {
        $field->setValue(@$data[$name]);
      }
    }
  }

  public function isValid($data = NULL) {
    if ($data === NULL) {
      
    } else {
      $this->setData($data);
    }

    $valid = true;
    foreach ($this->_fields as $name => $field) {
      $result = $field->isValid();
      if ($result == Validate::ERROR) {
        // invalid but not skip
        $valid = false;
      } else if ($valid == Validate::EXCEPTION) {
        return -2;
      }
    }
    return $valid;
  }

  public function getData() {
    $data = array();
    foreach ($this->_fields as $key => $field) {
      $data[$key] = $field->getValue();
    }
    return $data;
  }

  public function getValue($name) {
    if (($field = $this->_fields[$name]) == NULL) {
      throw new Exception("field $name doesn't not exists!");
    }
    return $field->getValue();
  }

  public function __set($name, $value) {
    if (!$value instanceof Field_Abstract) {
      throw new Exception($name . " isn't not a field!");
    }
    $this->_fields[$name] = $value;
  }

  public function __get($name) {
    if ($this->_fields[$name] == NULL) {
      throw new Exception('field ' . $name . " doesn't not exists!");
    }
    if (!$this->_fields[$name] instanceof Field_Abstract) {
      throw new Exception($name . " isn't not a field!");
    }
    return $this->_fields[$name];
  }

  public function setDescription($string) {
    $this->_desc = $desc;
    return $this;
  }

  public function setTitle($string) {
    $this->_title = $title;
    return $this;
  }

  public function getDescription() {
    return $this->_desc;
  }

  public function getTitle() {
    return $this->_title;
  }

  public function setExtras($params) {
    $params = (array) $params;
    foreach ($params as $key => $value) {
      $this->_extras[$key] = $value;
    }
    return $this;
  }

  public function getExtras() {
    $str = array();
    foreach ($this->_extras as $key => $value) {
      $str[] = sprintf('%s="%s"', $key, $value);
    }
    return implode(' ', $str);
  }

}
